// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
  cart:[],
  allchecked:false,
  totalPrice:0,
  totalNum:0,

  },
 
  onShow(){
    const cart=wx.getStorageSync('cart')||[];
    this.setData({
      cart
    })
    this.setCrt()
  },
  handleItemChange(e){
    const goodsId=e.currentTarget.dataset.id;
   
    let {cart} =this.data;
    let index=cart.findIndex(item=>item.goods_id===goodsId)
    cart[index].checked=!cart[index].checked;
    this.setCrt()
  },
  //封装购物车优化
  setCrt(cart){
     cart=this.data.cart
      let allchecked=true;
      //合计
      let totalPrice=0;
      //总数量
      let totalNum=0;
      cart.forEach(item=>{
        // 判断checked的状态是否为true,为true就计算
        if(item.checked){
          //为true就计算
          totalPrice+=item.num*item.goods_price;
          totalNum+=item.num
        }else{
          //默认值
          allchecked=false
        }
      })
        // 判断数组是否为空
      allchecked=cart.length!=0?allchecked:false,  
      this.setData({
        cart,totalPrice,totalNum,allchecked
      })
      wx.setStorageSync('cart', cart);
  },
  //全选反选
  handleItemCkall(){
    let {cart,allchecked}=this.data
    this.data.allchecked=!allchecked
    cart.forEach(item=>item.checked=this.data.allchecked)
    this.setData({
      cart,
     
    })
  
  },
 
  //编辑+-
  handleItemEdit(e){
    const {operation,id}=e.currentTarget.dataset;
    console.log(operation,id);
  let cart=this.data.cart
  const index=cart.findIndex(item=>item.goods_id===id)
    if(cart[index].num===1&&operation===-1){
      wx.showModal({
        title: '提示',
        content: '你是否要删除',
        success: (res)=> {
          if (res.confirm) {
           cart.splice(index,1)
           this.setData({cart})
          }
        }
      })

    }else{
      cart[index].num+=operation;
      this.setCrt(cart)
    }
  },
//结算功能
  handleClose(){
    let {totalNum} =this.data
    if (totalNum===0) {
    wx.showToast({
       title: '请选择商品'
     })
      return
    }
 wx.navigateTo({
   url: '/pages/pay/index',
 })
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
  },
  // 获取收货地址
  handleChooseAddress(){
    wx.chooseAddress({
      success: (result1) => {
        console.log(result1);
      }
    }) 
  },

  
     
 
})